package vulnerability

import (
	"fmt"

	v1 "github.com/anchore/grype-db/pkg/db/v1"
	"github.com/anchore/grype/grype/version"
	"github.com/anchore/syft/syft/pkg"
)

type Vulnerability struct {
	Constraint     version.Constraint
	CPEs           []pkg.CPE
	ID             string
	RecordSource   string
	FixedInVersion string
}

func NewVulnerability(vuln v1.Vulnerability) (*Vulnerability, error) {
	format := version.ParseFormat(vuln.VersionFormat)

	constraint, err := version.GetConstraint(vuln.VersionConstraint, format)
	if err != nil {
		return nil, fmt.Errorf("failed to parse constraint='%s' format='%s': %w", vuln.VersionConstraint, format, err)
	}

	return &Vulnerability{
		Constraint:     constraint,
		ID:             vuln.ID,
		CPEs:           make([]pkg.CPE, 0),
		RecordSource:   vuln.RecordSource,
		FixedInVersion: vuln.FixedInVersion,
	}, nil
}

func (v Vulnerability) String() string {
	return fmt.Sprintf("Vuln(id=%s constraint='%s')", v.ID, v.Constraint)
}

func (v *Vulnerability) hash() string {
	return fmt.Sprintf("%s|%s|%+v", v.ID, v.Constraint, v.CPEs)
}
